package com.fjsh.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 重写oAuth2异常
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        Throwable cause = e.getCause();
        Map<String,Object> map = new HashMap<>(16);
        String code;
        String message;
        if (cause instanceof InvalidTokenException) {
            code = "A0311";
            message = "请求失败，授权已过期";
        } else {
            code = "A0301";
            message = "请求失败，访问未授权";
        }
        map.put("code",code);
        map.put("message",message);
        httpServletResponse.getWriter().write(JSON.toJSONString(map));
    }
}
